package com.ruoyi.framework.datasource;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Map;

@Component
@AllArgsConstructor
public class RuntimeDataSourceSetting {


    private DynamicDataSource dynamicDataSource;

    private DataSource masterDataSource;

    /**
     * 动态设置新数据源
     *
     * @param dataSourceName 数据源名称
     * @param dataSource     数据源
     */
    public void setDataSource(String dataSourceName, DataSource dataSource) {
        Map<Object, Object> dataSources = dynamicDataSource.getDataSources();
        dataSources.put(dataSourceName, dataSource);
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource);
        dynamicDataSource.setTargetDataSources(dataSources);
        dynamicDataSource.afterPropertiesSet();
    }

    /**
     * 动态移除数据源
     *
     * @param dataSourceName 数据源名称
     */
    public void removeDataSource(String dataSourceName) {
        Map<Object, Object> dataSources = dynamicDataSource.getDataSources();
        dataSources.remove(dataSourceName);
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource);
        dynamicDataSource.setTargetDataSources(dataSources);
        dynamicDataSource.afterPropertiesSet();
    }

    public Map<Object, Object> getDataSource() {
        return dynamicDataSource.getDataSources();
    }
}
